package com.jiuyin.dianjing.app;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.multidex.MultiDex;

import com.activeandroid.ActiveAndroid;
import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.folder.PhotoPickOptionsConfig;
import com.jiuyin.dianjing.manager.AppManager;
import com.jiuyin.dianjing.oss.OssService;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.PMUtil;
import com.jiuyin.dianjing.util.SPFUtil;
import com.jiuyin.dianjing.util.TypefaceUtil;
import com.jiuyin.dianjing.util.Utils;
import com.lzh.easythread.EasyThread;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.rain.library.PhotoPick;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.Bugly;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import jiguang.entity.GlideImageLoader;
import jiguang.ui.view.CropImageView;
import jiguang.ui.view.ImagePicker;
import jiguang.util.SharePreferenceManager;
import jiguang.util.StorageUtil;
import me.leolin.shortcutbadger.ShortcutBadger;
import okhttp3.OkHttpClient;

import static com.jiuyin.dianjing.BuildConfig.BUGLY_APP_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_FIRST_LAUNCH;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_MOBILE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NICK_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.constant.AppConstant.KEY_JG_LAST_SYSTEM_MSG;
import static com.jiuyin.dianjing.constant.AppConstant.KEY_JG_NICKNAME;
import static com.jiuyin.dianjing.constant.AppConstant.KEY_JG_NUM_MSG;
import static com.jiuyin.dianjing.constant.AppConstant.KEY_JG_PASSWORD;
import static com.jiuyin.dianjing.constant.AppConstant.KEY_JG_USERNAME;

public class HelperApplication extends com.activeandroid.app.Application {
    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.colorAccent).setAccentColorId(android.R.color.white));
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.colorAccent).setAccentColorId(android.R.color.white));
    }

    public static OssService ossService;
    private static Context sContext;
    private static SPFUtil sSPFUtil;
    private static EasyThread sEasyThread;
    public static String THUMP_PICTURE_DIR;
    public static String PICTURE_DIR = "sdcard/JChatDemo/pictures/";
    public static int maxImgCount;               //允许选择图片最大数
    private static final String JCHAT_CONFIGS = "JChat_configs";

    /**
     * 昵称
     */
    private static String NickName = "";
    /**
     * 手机号即账户名
     */
    private static String Mobile = "";
    /**
     * Token
     */
    private static String Token = "";
    /**
     * ID
     */
    private static String ID = "";

    private static String JG_NAME = "";
    private static String JG_NICK_NAME = "";
    private static String JG_PWD = "";
    private static String JG_LAST_SYSTEM_MSG = "";
    private static int sMsgNumb = 0;

    public synchronized static void setBadger(int count) {
        if (ShortcutBadger.isBadgeCounterSupported(getContext())) {
            sMsgNumb = count;
            if (sMsgNumb >= 99) {
                sMsgNumb = 99;
            }
            sSPFUtil.putSpInt(KEY_JG_NUM_MSG, sMsgNumb);
            ShortcutBadger.applyCount(getContext(), sMsgNumb);
        }
    }

    public static void initBadger() {
        if (ShortcutBadger.isBadgeCounterSupported(getContext())) {
            ShortcutBadger.applyCount(getContext(), sMsgNumb);
        }
    }

    public static String getJgLastSystemMsg() {
        if (TextUtils.isEmpty(JG_LAST_SYSTEM_MSG)) {
            JG_LAST_SYSTEM_MSG = sSPFUtil.getSP(KEY_JG_LAST_SYSTEM_MSG);
        }
        return JG_LAST_SYSTEM_MSG;
    }

    public static void setJgLastSystemMsg(String id) {
        HelperApplication.JG_LAST_SYSTEM_MSG = id;
        sSPFUtil.putSP(KEY_JG_LAST_SYSTEM_MSG, id);
    }


    public static String getJgName() {
        if (TextUtils.isEmpty(JG_NAME)) {
            JG_NAME = sSPFUtil.getSP(KEY_JG_USERNAME);
        }
        return JG_NAME;
    }

    public static void setJgName(String id) {
        HelperApplication.JG_NAME = id;
        sSPFUtil.putSP(KEY_JG_USERNAME, id);
    }

    public static String getJgPwd() {
        if (TextUtils.isEmpty(JG_PWD)) {
            JG_PWD = sSPFUtil.getSP(KEY_JG_PASSWORD);
        }
        return JG_PWD;
    }

    public static void setJgPwd(String id) {
        HelperApplication.JG_PWD = id;
        sSPFUtil.putSP(KEY_JG_PASSWORD, id);
    }

    public static String getJgNickName() {
        if (TextUtils.isEmpty(KEY_JG_NICKNAME)) {
            JG_NICK_NAME = sSPFUtil.getSP(KEY_JG_NICKNAME);
        }
        return JG_NICK_NAME;
    }

    public static void setJgNickName(String id) {
        HelperApplication.JG_NICK_NAME = id;
        sSPFUtil.putSP(KEY_JG_NICKNAME, id);
    }


    public static String getID() {
        if (TextUtils.isEmpty(ID)) {
            ID = sSPFUtil.getSP(KEY_ID);
        }
        return ID;
    }

    public static void setID(String id) {
        HelperApplication.ID = id;
        sSPFUtil.putSP(KEY_ID, id);
    }

    public static String getToken() {
        if (TextUtils.isEmpty(Token)) {
            Token = sSPFUtil.getSP(KEY_TOKEN);
        }
        return Token;
    }

    public static void setToken(String token) {
        Token = token;
        sSPFUtil.putSP(KEY_TOKEN, token);
    }

    public static Context getContext() {
        return sContext;
    }


    public static String getNickName() {
        if (TextUtils.isEmpty(NickName)) {
            NickName = sSPFUtil.getSP(KEY_NICK_NAME);
        }
        return NickName;
    }

    public static void setNickName(String nickName) {
        NickName = nickName;
        sSPFUtil.putSP(KEY_NICK_NAME, nickName);

    }

    public static String getMobile() {
        if (TextUtils.isEmpty(Mobile)) {
            Mobile = sSPFUtil.getSP(KEY_MOBILE);
        }
        return Mobile;
    }

    public static void setMobile(String mobile) {
        Mobile = mobile;
        sSPFUtil.putSP(KEY_MOBILE, mobile);
    }

    public static String getHeader() {
        return sSPFUtil.getSP("header");
    }

    public static void setHeader(String header) {
        sSPFUtil.putSP("header", header);
    }

    public static String getUserId() {
        return sSPFUtil.getSP("userId");
    }

    public static void setUserId(String clientuser_id) {
        sSPFUtil.putSP("userId", clientuser_id);
    }

    public static void setLaunched() {
        sSPFUtil.putSPBoolean(KEY_FIRST_LAUNCH, false);
    }

    public static boolean isFirstLaunch() {
        return sSPFUtil.getSPBoolean(KEY_FIRST_LAUNCH, true);
    }

    /**
     * 获取线程池
     *
     * @return
     */
    public static EasyThread getEasyThread() {
        return sEasyThread;
    }

    /**
     * 清除token,HX pwd, HX userName,NickName,Mobile
     */
    public static void quitLogin() {
        setToken("");
        setNickName("");
        setJgName("");
        setJgPwd("");
        setJgNickName("");
        setJgLastSystemMsg("");
        sSPFUtil.putSpInt(KEY_JG_NUM_MSG, 0);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = this;
        THUMP_PICTURE_DIR = sContext.getFilesDir().getAbsolutePath() + "/JChatDemo";
        sSPFUtil = SPFUtil.getInstance(this);
        sMsgNumb = sSPFUtil.getSpInt(KEY_JG_NUM_MSG);
        init();
    }

    private void init() {
//        BugtagsOptions options = new BugtagsOptions.Builder().
//                trackingLocation(true).//是否获取位置，默认 true
//                trackingCrashLog(true).//是否收集crash，默认 true
//                trackingConsoleLog(true).//是否收集console log，默认 true
//                trackingUserSteps(true).//是否收集用户操作步骤，默认 true
//                trackingNetworkURLFilter(null).//自定义网络请求跟踪的 url 规则，默认 null
//                build();
//        Bugtags.start("5c723948b4f16981c534447b190eeb06", this, Bugtags.BTGInvocationEventBubble,options);
        registerActivityListener();
//        CityListLoader.getInstance().loadProData(this);
        Utils.init(this);
        AppManager.init(getContext());
//        initEaseIm();
//        baiduMapInit();
        initEasyThread();
        umengInit();
        initOkGo();
        initImageLoader();
        initOSS();
        buglyInit();
        jPushInit();
        PhotoPick.init(getApplicationContext(), PhotoPickOptionsConfig.getPhotoPickOptions(getContext()));
        StorageUtil.init(getContext(), null);
        Fresco.initialize(getApplicationContext());
        SharePreferenceManager.init(getApplicationContext(), JCHAT_CONFIGS);
        initImagePicker();
        initBadger();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    /***
     * 极光初始化
     */
    private void jPushInit() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(getApplicationContext());
        JMessageClient.setDebugMode(true);
        JMessageClient.init(getContext(), true);
    }

    private void buglyInit() {
        Bugly.init(getApplicationContext(), BUGLY_APP_ID, false);
    }

    private void initOSS() {
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        //if null , default will be init
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // connction time out default 15s
        conf.setSocketTimeout(15 * 1000); // socket timeout，default 15s
        conf.setMaxConcurrentRequest(5); // synchronous request number，default 5
        conf.setMaxErrorRetry(2); // retry，default 2        OSSLog.enableLog(); //write local log file ,path is SDCard_path\OSSLog\logs.csv
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("LTAI4FkkiwvUpfk81zaAoRP8", "HkA9LUodrASwZkfRZaJbkvNQirbX7C", "");
        //https://github.com/aliyun/aliyun-oss-android-sdk?spm=a2c4g.11186623.2.11.35c42c66KktX89
        //https://help.aliyun.com/document_detail/32044.html?spm=a2c4g.11186623.6.1191.2c0b2841OMRZAw
        //https://help.aliyun.com/document_detail/32046.html?spm=a2c4g.11186623.2.21.6c8f2d71jtU1Wi#title-7no-891-5u9
        new Thread(() -> {
            OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
            ossService = new OssService(oss);
        }).start();
    }


    /**
     * okGo 网络请求
     */
    private void initOkGo() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //第三方的开源库，使用通知显示当前请求的log，不过在做文件下载的时候，这个库好像有问题，对文件判断不准确
        //builder.addInterceptor(new ChuckInterceptor(this));

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失

        // 其他统一的配置
        // 详细说明看GitHub文档：https://github.com/jeasonlzy/
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
    }

    /**
     * 友盟初始化
     */
    private void umengInit() {
        //使用AndroidManifest.xml中配置过appkey和channel值
        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null);
        UMConfigure.setLogEnabled(true);
        UMConfigure.setEncryptEnabled(true);
        //appid, appkey
        PlatformConfig.setWeixin("wx73c81388d9441539", "4538c750c9885da71e3438fea7a6cb14");
        //参数3位回调地址
        PlatformConfig.setSinaWeibo("2589362774", "9527f9ea5fb9f9c91c1795ac6a52acd3", "http://sns.whalecloud.com");
    }

    private void test() {
        LogUtil.log("test " + DisplayUtil.sp2px(getContext(), 1.0f));
    }

    private void registerActivityListener() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                PMUtil.getInstance().pushAC(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                PMUtil.getInstance().removeAC(activity);
            }
        });
    }

    /**
     * 更改字体
     */
    private void applyTtf() {
        TypefaceUtil.replaceSystemDefaultFont(this, "fonts/FZJHJW.ttf");
    }

//    private void baiduMapInit() {
//        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
//        SDKInitializer.initialize(this);
//        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
//        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
//        SDKInitializer.setCoordType(CoordType.BD09LL);
//    }

    /**
     * 初始化线程池
     */
    private void initEasyThread() {
        sEasyThread = EasyThread.Builder.createSingle().build();
    }

    private void initImageLoader() {
        ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(this);
        ImageLoader.getInstance().init(configuration);
    }

//    private void initImagePicker() {
//        ImagePicker imagePicker = ImagePicker.getInstance();
//        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
//        imagePicker.setShowCamera(true);                      //显示拍照按钮
//        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
//        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
//        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
//        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
//        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
//        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
//        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
//    }

    public static void setPicturePath(String appKey) {
        if (!SharePreferenceManager.getCachedAppKey().equals(appKey)) {
            SharePreferenceManager.setCachedAppKey(appKey);
            PICTURE_DIR = "sdcard/JChatDemo/pictures/" + appKey + "/";
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ActiveAndroid.dispose();
    }
}
